<?php

namespace App\Http\Controllers\Site;

use App\B2BProject\Area;
use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Custom\MemberInformation;
use App\B2BProject\Custom\Provider\Offer;
use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\AuthorizationRequest;
use App\B2BProject\Custom\Business\GoodsCategory;
use App\B2BProject\Custom\Member;
use Auth;
use App\B2BProject\Custom\Business\Store;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\B2BProject\Exception\UserTypeException;

class StoreController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * 店铺首页
     * @return string
     */
    public function getIndex($id)
    {
        //店铺的id，读取店铺的信息

        $store = Store::where('id', $id)->firstOrFail();

        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();
        $category    = '';
        $auth_addr   = "/store/$id/authorization-request";

        return view('host.store.store')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('categorydata', $category)->with('auth_addr', $auth_addr);
    }

    /**
     * 根据分类显示商品
     * @param $store_id
     * @param $category_id
     * @return $this
     */

    public function getCategory($store_id, $category_id)
    {
        //店铺的id，读取店铺的信息
        $category    = $category_id;
        $store       = Store::where('id', $store_id)->firstOrFail();
        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();
        $auth_addr   = "/store/$store_id/authorization-request";
        return view('host.store.store')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('categorydata', $category)->with('auth_addr', $auth_addr);
    }

    /**
     * 公司介绍
     * @param $id
     * @return $this
     */
    public function getCompany($id)
    {

        $store       = Store::where('id', $id)->firstOrFail();
        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();

        $auth_addr = "/store/$id/authorization-request";
        return view('host.store.company')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('auth_addr', $auth_addr);
    }

    /**
     * 招商信息
     * @param $id
     * @return $this
     */
    public function getCanvass($id)
    {

        $store       = Store::where('id', $id)->firstOrFail();
        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();

        $auth_addr = "/store/$id/authorization-request";
        return view('host.store.canvass')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('auth_addr', $auth_addr);
    }

    /**
     * 产品页面
     * @param $id
     * @return $this
     */
    public function getProduct($id)
    {
        //id 为店铺id
        $store       = Store::where('id', $id)->firstOrFail();
        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();
        $auth_addr   = "/store/$id/authorization-request";

        return view('host.store.product')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('auth_addr', $auth_addr);
    }

    /**
     * 产品列表信息显示
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProductList(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('perpage', $request->pageSize));
        $goods = Goods::where('store_id', $request->query('cid'))->display()->where('strict_lock',
            false)->paginate($request->query('pageSize',
            7));

        $data = [];
        foreach ($goods as $good) {
            $item['id']     = $good->id;
            $item['name']   = $good->name;
            $item['href']   = route('goods.detail', [$good->id]);
            $item['num']    = $good->stock;
            $item['minnum'] = $good->minimum_order;
            $item['imgsrc'] = $good->cover();
            $item['addr']   = Area::getName($good->provonce_id) .
                ' ' .
                Area::getName($good->city_id);
            $item['time']   = date('Y-m-d', strtotime($good->create_at));


            $item['price'] = $good->original_price;
            if (\Auth::check()) { //  已登陆状态
                if ($good->grant_status == '0') {     //判断是否是自由集散区的商品
                    $item['price'] = $good->original_price;
                } else {
                    if (\Auth::user()->class == 2) {  // 采购商身份
                        if ($good->isGranted()) {//判断是否授权
                            $item['price'] = $good->original_price * $good->getPriceStrategy();
                        } else {
                            $item['price'] = '未授权';
                        }
                    } else {  //供应商身份
                        $member = \Auth::user();
                        if (Goods::where('store_id',
                            Store::where('member_id', $member->id)->first()->id)->first()
                        ) {   // 供应商有自己的店铺
                            if (Goods::where('store_id',
                                    Store::where('member_id',
                                        $member->id)->first()->id)->first()->store_id == $good->store->id
                            ) { //供应商自己的店铺
                                $item['price'] = '￥' . $good->original_price;
                            } else {
                                $item['price'] = '未授权';
                            }
                        } else {
                            $item['price'] = '未授权';
                        }
                    }
                }
            } else {//未登陆状态
                if ($good->grant_status == '0') {     //判断是否是自由集散区的商品
                    $item['price'] = $good->original_price;
                } else {
                    $item['price'] = "请登录后查看";
                }
            }

            $data[] = $item;
        }
        return response()->json([
            'data'           => $data,
            'pagingConfData' => [
                'page'     => $request->query('page'),
                'pageSize' => $request->query('pageSize'),
                'total'    => $goods->total(),
            ],
        ]);
    }


    /**
     * 报盘信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function getInfo(Request $request, $id = null)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        if ($request->ajax()) {

            $storeId = $request->query('cid');

            $member_id = Store::findOrFail($storeId)->member->id;
            $info      = Offer::where('member_id', $member_id)->paginate($request->query('pageSize', 7));

            $listData = [];
            foreach ($info as $list) {
                $item = [
                    'id'      => $list->id,
                    'href'    => route('goods.detail', [$list->id]),
                    'proname' => $list->title,
                    'name'    => $list->title,
                    'minnum'  => $list->minimum_order,
                    'num'     => $list->amount,
                    'addr'    => Area::where('id',
                            $list->province_id)->first()->name . ' ' . Area::where('id', $list->city_id)->first()->name,
                    'time'    => date('Y-m-d', strtotime($list->created_at))
                ];
                if (\Auth::check()) { //  已登陆状态
                    $item['price'] = '￥' . $list->price;
                } else {//未登陆状态
                    $item['price'] = "请登录后查看";
                }
                $listData[] = $item;
            }
            return response()->json([
                'data'           => $listData,
                'pagingConfData' => [
                    'page'     => $info->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $info->total(),
                ],
            ]);
        }

        $store       = Store::where('id', $id)->firstOrFail();
        $information = $store->member->information;
        $member      = Member::where('id', $store->member_id)->firstOrFail();
        $auth_addr   = "/store/$id/authorization-request";
        return view('host.store.supply')->with('storeInfo', $store)->with('information',
            $information)->with('menberinfo',
            $member)->with('auth_addr', $auth_addr);
    }

    /**
     * 供应商申请授权
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function getAuthorizationRequest($id)
    {
        //判断是否是采购商 则进行验证
        try {
            $store = Store::where('id', $id)->firstOrFail();

            if (Auth::user()->class == 2) {
                return view('host.authorization')->with('supplier_id', $id)->with('store_id', $store->id);
            }
            // 用户类型不匹配，抛出异常
            throw new UserTypeException;

        } catch (ModelNotFoundException $e) {
            return response('访问的资源不存在', 404);
        } catch (UserTypeException $e) {
            // TODO  在此应当标明提示信息，否则客户端不知道发生了什么就跳转
            return response($e->getMessage(), 403);
        }
    }

    /**
     * 授权
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function postAuthorizationRequest(Request $request, $id)
    {
        try {
            if (Auth::user()->isPurchaser()) {
                // 获取供应商
                $store = Store::where('id', $id)->firstOrFail();

                // 先进行验证是否存在有效的授权，若存在则不应当继续进行
                if ($store->isGranted(Auth::id())) {
                    return response('已存在有效授权', 403);
                }

                // 判断是否有正在进行中的授权
                if ($store->member->authorizationRequests()->Pending()->count() > 0) {
                    return response('已存在正在等待受理的授权申请', 403);
                }

                $validator = Validator::make(
                    $request->all(),
                    [
                        'company_name'  => 'required',  //验证公司名称
                        'contact_name'  => "required",
                        'contact_phone' => 'required',
                        'contact_email' => 'required|email',
                        'message'       => 'required',
                        'sex'           => 'required|boolean',
                    ]
                );

                if ($validator->fails()) {
                    return redirect()->back()->withErrors($validator);
                }

                \DB::transaction(function () use ($request, $store) {
                    $data = $request->only([
                        'company_name',
                        'contact_phone',
                        'contact_name',
                        'contact_email',
                        'message',
                        'sex',
                    ]);// 只取这些数据

                    $authorizationRequest = AuthorizationRequest::create($data);

                    Auth::user()->purchaserAuthorizationRequests()->save($authorizationRequest);

                    $store->member->authorizationRequests()->save($authorizationRequest);
                });
                //跳转至采购商中心的我的申请页面
                return redirect()->route('account.purchaser.my-authorization-request.index');
            } else {
                throw new UserTypeException;
            }
        } catch (\BadMethodCallException $e) {
            return response($e->getMessage(), 403);
        } catch (UserTypeException $e) {
            return response($e->getMessage(), 403);
        } catch (ModelNotFoundException $e) {
            return response('404 Not found', 404);
        } catch (\Exception $e) {
            // TODO  在此应当标明提示信息，否则客户端不知道发生了什么就跳转
            throw $e;
        }
    }

    /**
     * 查找相关的店铺信息  公共类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreCategory(Request $request)
    {

        //根据店铺id查找相关的店铺分类
        $store_id = $request->query('cid');

        $parents = GoodsCategory::getStoreCategory($store_id);
        foreach ($parents as $parent) {
            $item = [
                'id'      => $parent->id,
                'name'    => $parent->name,
                'hrefVal' => route('store.category', [$store_id, $parent->id])
            ];
            foreach ($parent->children as $child) {
                $item['children'][] = [
                    'id'      => $child->id,
                    'name'    => $child->name,
                    'hrefVal' => route('store.category', [$store_id, $child->id])
                ];
            }

            $data['data']['storeClassify'][] = $item;
        }
        //查找company信息
        $store                    = Store::where('id', $store_id)->firstOrFail();
        $information              = $store->member->information;
        $member                   = \Auth::user();
        $data['data']['baseInfo'] = [
            'id'            => $information->id,
            'logo'          => $store->store_logo,
            'name'          => $information->company,
            'storekeeper'   => Member::where('id', Store::where('id', $store->id)->first()->member_id)->first()->user,
            'creditLimit'   => '6',
            'storeGrade'    => ['普通', '白金', '钻石'][$store->level - 1],
            'goodAmount'    => Goods::where('store_id', $store_id)->count(),
            'region'        => Area::getName($information->province_id) . ' ' . Area::getName($information->city_id) . ' ' . Area::getName($information->county_id),
            'certification' => $store->real_name_authentication ? '\assets\b2b\css\images\name_a.png' : '',
            'provider_authentication'          => $store->provider_authentication ? '\assets\b2b\css\images\supply_a.png' : '',
            'addr'          => $information->address,
            'contactPhone'  => $store->contact_phone,
            'createTime'    => date('Y-m-d', strtotime($store->created_at)),
        ];

        if (\Auth::check()) { //  已登陆状态
            if (\Auth::user()->class == 2) {  // 采购商身份
                if ($store->isGranted()) {
                    $data['data']['baseInfo']['authorityState'] = "已授权";
                } else {
                    $data['data']['baseInfo']['authorityState'] =
                        "未授权  " . "<a href='/store/$store_id/authorization-request' class='tn btn-default btn-w70x32 mt60 unauthorized'>申请授权</a>";
                }
            } else {  // 供应商身份
                $member = \Auth::user();
                if (Goods::where('store_id',
                    Store::where('member_id', $member->id)->first()->id)->first()
                ) {   // 供应商有自己的店铺
                    if (Goods::where('store_id',
                            Store::where('member_id', $member->id)->first()->id)->first()->store_id == $store->id
                    ) { //供应商自己的店铺
                        $data['data']['baseInfo']['authorityState'] = '';
                    } else {
                        $data['data']['baseInfo']['authorityState'] = '未授权';
                    }
                } else {
                    $data['data']['baseInfo']['authorityState'] = '未授权';
                }
            }
        } else {//未登陆状态
            $data['data']['baseInfo']['authorityState'] = $store->isGranted();
        }
        return response()->json($data);
    }
}
